package com.sunfeng.n4.deadlock;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntBinaryOperator;
import java.util.function.IntUnaryOperator;

/**
 * Unary  一元操作
 */
public class Test34 {
    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(5);


        updateAndGet(atomicInteger, value -> value - 1);


        System.out.println(atomicInteger.get());
    }


    public static int updateAndGet(AtomicInteger atomicInteger, IntUnaryOperator intUnaryOperator) {
        int prev, next;
        while (true) {
            prev = atomicInteger.get();
            next = intUnaryOperator.applyAsInt(prev);
            if (atomicInteger.compareAndSet(prev, next)) {
                return next;
            }
        }

    }
}
